#include <zephyr.h>
#include <drivers/uart.h>
#include <net/mqtt.h>
#include <net/socket.h>
#include <stdio.h>

#define SERVER_ADDR "mqtt.rescue-platform.com"
#define SERVER_PORT 1883
#define CLIENT_ID "autorescue_001"
#define TOPIC "vehicle/emergency"

static struct mqtt_client client;
static struct sockaddr_storage broker;

int init_mqtt_connection(void) {
    int ret;
    struct sockaddr_in *broker4 = (struct sockaddr_in *)&broker;
    
    broker4->sin_family = AF_INET;
    broker4->sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_ADDR, &broker4->sin_addr);
    
    mqtt_client_init(&client);
    
    client.broker = &broker;
    client.client_id.utf8 = CLIENT_ID;
    client.client_id.size = strlen(CLIENT_ID);
    
    ret = mqtt_connect(&client);
    if (ret != 0) {
        printf("MQTT连接失败: %d\n", ret);
        return -1;
    }
    
    return 0;
}

void send_emergency_signal(void) {
    char payload[128];
    snprintf(payload, sizeof(payload), 
             "{\"type\":\"collision\",\"action\":\"door_release\"}");
    
    struct mqtt_publish_param param = {
        .message.topic.qos = MQTT_QOS_0_AT_MOST_ONCE,
        .message.topic.topic.utf8 = TOPIC,
        .message.topic.topic.size = strlen(TOPIC),
        .message.payload.data = payload,
        .message.payload.len = strlen(payload),
        .dup_flag = 0,
        .retain_flag = 0
    };
    
    int ret = mqtt_publish(&client, &param);
    if (ret != 0) {
        printf("MQTT发布失败: %d\n", ret);
    }
}

int init_4g_module(void) {
    const struct device *uart_dev = device_get_binding("UART_1");
    if (!uart_dev) {
        return -1;
    }
    
    const char *init_cmds[] = {
        "AT",
        "AT+CPIN?",
        "AT+CREG?",
        "AT+CGATT=1",
        "AT+CGDCONT=1,\"IP\",\"CMNET\"",
        "AT+CGACT=1,1"
    };
    
    for (int i = 0; i < sizeof(init_cmds)/sizeof(init_cmds[0]); i++) {
        if (send_at_command(uart_dev, init_cmds[i]) != 0) {
            return -2;
        }
    }
    
    return 0;
}

void send_gps_location(void) {
}